Imports System.Text

<CLSCompliant(True)> _
Public Class TextBoxWriter
    Inherits System.IO.TextWriter

    Private control As TextBoxBase
    Private Builder As StringBuilder

    <CLSCompliant(False)> _
    Public Event Results(ByVal sender As Object, ByVal e As XMLEventArgs)

    Private Delegate Sub AppendText1(ByVal value As String)

    Public Sub New(ByVal control As RichTextBox)
        Me.control = control
        AddHandler control.HandleCreated, New EventHandler(AddressOf OnHandleCreated)
    End Sub

    Public Overrides Sub Write(ByVal value As Char)
        Write(value.ToString())
    End Sub

    Public Overrides Sub Write(ByVal value As String)
        If (control.IsHandleCreated) Then : AppendText(value)
        Else : BufferText(value)
        End If
    End Sub

    Public Overrides Sub WriteLine(ByVal value As String)
        Write(value + Environment.NewLine)
    End Sub

    Private Sub BufferText(ByVal value As String)
        If (Builder Is Nothing) Then Builder = New StringBuilder()
        Builder.Append(value)
    End Sub

    Private Sub AppendText(ByVal value As String)
        If control.InvokeRequired Then : control.Invoke(New AppendText1(AddressOf AppendText), value)
        Else
            If Not Builder Is Nothing Then
                control.AppendText(Builder.ToString())
                Builder = Nothing
            End If
            If value.Trim <> String.Empty Then RaiseEvent Results(Me, New XMLEventArgs(value))

            control.AppendText(value)
        End If
    End Sub

    Private Sub OnHandleCreated(ByVal sender As Object, ByVal e As EventArgs)
        If Not Builder Is Nothing Then
            control.AppendText(Builder.ToString())
            Builder = Nothing
        End If
    End Sub

    Public Overrides ReadOnly Property Encoding() As System.Text.Encoding
        Get
            Return Encoding.Default
        End Get
    End Property

End Class

Public Class XMLEventArgs
    Inherits EventArgs

    Private _xmlResult As String

    Public Property XmlResult() As String
        Get
            XmlResult = _xmlResult
        End Get
        Set(ByVal value As String)
            _xmlResult = value
        End Set
    End Property

    Public Sub New(ByVal xmlResult As String)
        _xmlResult = xmlResult
    End Sub


End Class

